﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.Host;
using DWF.Studio.ISerivces;
using DWF.Studio.NuGetManagement;
using DWF.Studio.Project;
using DWF.Studio.Services;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// 活动包管理窗体
    /// </summary>
    public partial class WindowPackageManagement
    {
        /// <summary>
        /// 窗口属性
        /// </summary>
        public static PackagePageStatus packagePageStatus;
        /// <summary>
        /// 工程管理
        /// </summary>
        private ProjectManager _projectManager = null;
        /// <summary>
        /// 所有安装卸载的工程依赖包集合
        /// </summary>
        public static List<NugetPackageWrap> _currentPackageWrapList = null;

        private bool isLoadPackage = false;
        public WindowPackageManagement(string packageName="")
        {
            InitializeComponent();
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init(packageName);
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        private async void init(string packageName = "")
        {
            _projectManager = ProjectManager.Instance;

            _currentPackageWrapList = new List<NugetPackageWrap>();

            bool loadPackageList;

            packagePageStatus = PackagePageStatus.installedPackageShow;
            refreshBtnColor(packagePageStatus);

            this.installedPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/InstalledPackagepressed.png", UriKind.Relative));
            loadPackageList = await uCtrlPackageList.RefreshPage(packageName);
            uCtrlPackageDetail.RefreshPage();
            if (loadPackageList)
            {
                this.refreshBtn();
                var package = this.uCtrlPackageList.Selection();
                if (package != null)
                {
                    GlobalActionHandler.PackageSelected(new TagEventArgs<NugetPackageWrap>(package));
                }
            }

        }
        #region 菜单按钮事件
        /// <summary>
        /// 包源管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void packageSourceManager_Click(object sender, RoutedEventArgs e)
        {
            if (packagePageStatus == PackagePageStatus.packageSourceManagerShow)
            {
                return;
            }
            else
            {
                packagePageStatus = PackagePageStatus.packageSourceManagerShow;
                refreshBtnColor(packagePageStatus);
                this.uCtrlPackageSourceManagement.Visibility = Visibility.Visible;
                this.uCtrlPackageDetail.Visibility = Visibility.Collapsed;
                this.uCtrlPackageList.Visibility = Visibility.Collapsed;
                this.packageSourceManager_img.Source = new BitmapImage(new Uri("../Resources/Package/Settingpressed.png", UriKind.Relative));
            }
            this.refreshBtn();
        }
        /// <summary>
        /// 已安装的包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void installedPackage_Click(object sender, RoutedEventArgs e)
        {
            bool loadPackageList;
            if (packagePageStatus == PackagePageStatus.installedPackageShow)
            {
                return;
            }
            else
            {
                packagePageStatus = PackagePageStatus.installedPackageShow;
                refreshBtnColor(packagePageStatus);
                this.uCtrlPackageSourceManagement.Visibility = Visibility.Collapsed;
                this.uCtrlPackageDetail.Visibility = Visibility.Visible;
                this.uCtrlPackageList.Visibility = Visibility.Visible;
                this.installedPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/InstalledPackagepressed.png", UriKind.Relative));
                loadPackageList = await uCtrlPackageList.RefreshPage();
                uCtrlPackageDetail.RefreshPage();
            }
            if (loadPackageList)
            {
                this.refreshBtn();
            }
        }

        /// <summary>
        /// 本地包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void localPackage_Click(object sender, RoutedEventArgs e)
        {
            if (packagePageStatus == PackagePageStatus.localPackageShow)
            {
                return;
            }
            else
            {
                packagePageStatus = PackagePageStatus.localPackageShow;
                refreshBtnColor(packagePageStatus);
                this.uCtrlPackageSourceManagement.Visibility = Visibility.Collapsed;
                this.uCtrlPackageDetail.Visibility = Visibility.Visible;
                this.uCtrlPackageList.Visibility = Visibility.Visible;
                this.localPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/Localpressed.png", UriKind.Relative));
                await uCtrlPackageList.RefreshPage();
                uCtrlPackageDetail.RefreshPage();
            }
            this.refreshBtn();
        }
        /// <summary>
        /// 网络包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void networkPackage_Click(object sender, RoutedEventArgs e)
        {
            bool loadPackageList;
            if (packagePageStatus == PackagePageStatus.networkPackageShow)
            {
                return;
            }
            else
            {
                packagePageStatus = PackagePageStatus.networkPackageShow;
                refreshBtnColor(packagePageStatus);
                this.uCtrlPackageSourceManagement.Visibility = Visibility.Collapsed;
                this.uCtrlPackageDetail.Visibility = Visibility.Visible;
                this.uCtrlPackageList.Visibility = Visibility.Visible;
                this.networkPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/Netpressed.png", UriKind.Relative));
                loadPackageList = await uCtrlPackageList.RefreshPage();
                uCtrlPackageDetail.RefreshPage();
            }
            if (loadPackageList)
            {
                this.refreshBtn();
            }
        }
        /// <summary>
        /// 自定义包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void customPackage_Click(object sender, RoutedEventArgs e)
        {
            bool loadPackageList;
            if (packagePageStatus == PackagePageStatus.customPackageShow)
            {
                return;
            }
            else
            {
                packagePageStatus = PackagePageStatus.customPackageShow;
                refreshBtnColor(packagePageStatus);
                this.uCtrlPackageSourceManagement.Visibility = Visibility.Collapsed;
                this.uCtrlPackageDetail.Visibility = Visibility.Visible;
                this.uCtrlPackageList.Visibility = Visibility.Visible;
                this.customPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/Custompressed.png", UriKind.Relative));
                loadPackageList = await uCtrlPackageList.RefreshPage();
                uCtrlPackageDetail.RefreshPage();
            }
            if (loadPackageList)
            {
                this.refreshBtn();
            }
        }

        private void refreshBtnColor(PackagePageStatus packagePageStatus)
        {
            this.packageSourceManager_border.Background = null;
            this.packageSourceManager.IsEnabled = false;
            this.installedPackage_border.Background = null;
            this.installedPackage.IsEnabled = false;
            this.localPackage_border.Background = null;
            this.localPackage.IsEnabled = false;
            this.networkPackage_border.Background = null;
            this.networkPackage.IsEnabled = false;
            this.customPackage_border.Background = null;
            this.customPackage.IsEnabled = false;

            this.btnFinishInstall.IsEnabled = false;
            this.btnFinishCancel.IsEnabled = false;

            this.uCtrlPackageList.IsEnabled = false;

            this.packageSourceManager_img.Source = new BitmapImage(new Uri("../Resources/Package/Settingnormal.png", UriKind.Relative));
            this.installedPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/InstalledPackagenormal.png", UriKind.Relative));
            this.localPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/Localnormal.png", UriKind.Relative));
            this.networkPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/Netnormal.png", UriKind.Relative));
            this.customPackage_img.Source = new BitmapImage(new Uri("../Resources/Package/Customnormal.png", UriKind.Relative));
            SolidColorBrush brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E9E9E9"));
            switch (packagePageStatus)
            {
                case PackagePageStatus.packageSourceManagerShow:
                    this.packageSourceManager_border.Background = brush;
                    break;
                case PackagePageStatus.installedPackageShow:
                    this.installedPackage_border.Background = brush;
                    break;
                case PackagePageStatus.localPackageShow:
                    this.localPackage_border.Background = brush;
                    break;
                case PackagePageStatus.networkPackageShow:
                    this.networkPackage_border.Background = brush;
                    break;
                case PackagePageStatus.customPackageShow:
                    this.customPackage_border.Background = brush;
                    break;
            }
        }

        private void refreshBtn()
        {
            this.packageSourceManager.IsEnabled = true;
            this.installedPackage.IsEnabled = true;
            this.localPackage.IsEnabled = true;
            this.networkPackage.IsEnabled = true;
            this.customPackage.IsEnabled = true;
            this.uCtrlPackageList.IsEnabled = true;

            this.btnFinishInstall.IsEnabled = true;
            this.btnFinishCancel.IsEnabled = true;
        }
        #endregion

        #region 保存取消按钮
        /// <summary>
        /// 包更改 多个包变更
        /// </summary>
        /// <param name="newPackage"></param>
        /// <param name="isUninstall"></param>
        private void multiplePackageChange(List<NugetPackageWrap> newPackage)
        {
            WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_UnloadDesignerCtrl"));
            GlobalActionHandler.PackageChanging?.Invoke(EventArgs.Empty);
            var loader = RemoteLoaderHost.GetCurrentInstance();
            if (loader != null)
            {
                loader.Unload();//卸载控件程序域
            }
            WindowLoading.SetContent(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_LoadDesignerCtrl"));
            RemoteLoaderHost.CreateInstance(_projectManager.GetProjectProperties, _projectManager.GetDependOnPackageInfos());
            GlobalActionHandler.PackageChanged?.Invoke(EventArgs.Empty);
            if (newPackage.Count > 0)//判断错误的活动报
            {
                var installPackageName = "";
                var uninstallPackageName = "";
                var updatePackageName = "";
                for (int i = 0; i < newPackage.Count; i++)
                {
                    if (newPackage[i].PackageOperationType == PackageOperationType.Install)
                    {
                        installPackageName += newPackage[i].Id + newPackage[i].Version + "\n";
                    }
                    else if (newPackage[i].PackageOperationType == PackageOperationType.UnInstall)
                    {
                        uninstallPackageName += newPackage[i].Id + newPackage[i].Version + "\n";
                    }
                    else
                    {
                        updatePackageName += newPackage[i].Id + newPackage[i].Version + "\n";
                    }
                }
                var msgProperties1 = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_OK"),
                    Image = MessageBoxImage.Warning,
                    Text = $"{installPackageName} {uninstallPackageName}{updatePackageName}" + LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_MsgBox_Msg_ChangePackage"),
                    Title = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_MsgBox_Caption_ChangePackage"),
                };
                Window owner = Window.GetWindow(this);
                WindowLoading.CloseWindow();
                WpfMessageBox.Show(owner, ref msgProperties1);
            }
        }
        /// <summary>
        /// 完成安装
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnFinishInstall_Click(object send5er, RoutedEventArgs e)
        {
            if (_currentPackageWrapList != null && _currentPackageWrapList.Count > 0)//获得所有安装卸载包的数组
            {
                isLoadPackage = true;
                Window parentWindow = Window.GetWindow(this);
                WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_InstallPackage"), parentWindow);
                GlobalActionHandler.PackagePrechange?.Invoke(EventArgs.Empty);
                List<NugetPackageWrap> errorNugetPackage = new List<NugetPackageWrap>();
                try
                {
                    errorNugetPackage = await _projectManager.BatchOperationlPackage(_currentPackageWrapList);
                }
                catch (Exception ex)
                {
                    throw new CustomException(LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_MsgBox_Msg_ChangePackage"), ex);
                }
                finally
                {
                    multiplePackageChange(errorNugetPackage);
                }
            }
            _currentPackageWrapList = null;//清空list
            isLoadPackage = false;
            WindowLoading.CloseWindow();
            Window.GetWindow(this).Close();
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (isLoadPackage)
            {
                e.Cancel = true;
            }
        }
        /// <summary>
        /// 取消安装
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFinishCancel_Click(object sender, RoutedEventArgs e)
        {
            _currentPackageWrapList = null;
            Window.GetWindow(this).Close();
        }
        #endregion
        /// <summary>
        /// 渲染搜索框不然报错
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DialogWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.uCtrlPackageSourceManagement.Visibility = Visibility.Collapsed;
            this.uCtrlPackageDetail.Visibility = Visibility.Visible;
            this.uCtrlPackageList.Visibility = Visibility.Visible;
        }
    }
}
